package com.lucenten.collect.gnss.handler.tools;

import com.lucenten.collect.exec.ShellRun;
import com.lucenten.collect.gnss.entity.GnssFile;
import com.lucenten.collect.utils.FileUtils;
import com.lucenten.mq.SendJmsInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class IgsUnzip {
//

    public static boolean analysisDZ(GnssFile gnssFile, String fileName,Path tmpPath,Path nPath,Path gPath,Path mPath,final String run) {
        Path parent = gnssFile.getFile().getParent();
        String orgName = gnssFile.getFile().getFileName().normalize().toString();
        orgName = orgName.substring(0,orgName.lastIndexOf(".") -1);
        // 解压N文件
        unzip(parent.resolve(orgName+"n").normalize().toString(), fileName+"n",nPath,gnssFile);
        // 解压G文件
        unzip(parent.resolve(orgName+"g").normalize().toString(), fileName+"g",gPath,gnssFile);
        // 解压M文件
        unzip(parent.resolve(orgName+"m").normalize().toString(), fileName+"m",mPath,gnssFile);

        gnssFile.getDirFiles().add(fileName+"o");
        Path dPath = tmpPath.resolve(fileName+"d");
//        FileUtils.copy(gnssFile.getFile(),dPath, true);
        FileUtils.unZ(gnssFile.getFile(), dPath);
        gnssFile.addClear(dPath.normalize().toString());
        // 转换出O文件
        if (Files.exists(tmpPath.resolve(fileName+"o"))) {
            FileUtils.delete(tmpPath.resolve(fileName+"o"));
        }
        ShellRun.execOutPut(run+" "+dPath.normalize().toString());

        return true;
    }

    private static void unzip(String parent, String fileName,Path target,GnssFile gnssFile) {
        Path source = Paths.get(parent + ".Z");
        if (Files.exists(source)) {
            gnssFile.addBack(source.normalize().toString());
            gnssFile.getDirFiles().add(fileName);
            FileUtils.unZ(source, target);
//            SendJmsInfo.sendGnssMq(5, fileName, 0);
            return;
        }
        source = Paths.get(parent + ".z");
        if (Files.exists(source)) {
            gnssFile.addBack(source.normalize().toString());
            gnssFile.getDirFiles().add(fileName);
            FileUtils.unZ(source, target);
//            SendJmsInfo.sendGnssMq(5, fileName, 0);
            return;
        }
    }
}
